package com.imooc.BST;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * 二分搜索树
 * 父亲节点比左子树所有节点都大，比右子树所有节点都小
 */
public class BST<E extends Comparable<E>> {

    private class Node{
        private E e;
        private Node left, right;

        public Node(E e) {
            this.e = e;
            this.left = null;
            this.right = null;
        }
    }

    private Node root;
    private int size;

    public BST(){
        root = null;
        size = 0;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 插入元素
     * @param e
     */
    public void add(E e) {
        root = add(root, e);
    }

    /**
     * 插入元素核心递归函数
     * 返回新插入节点的根
     * @param node
     * @param e
     */
    private Node add(Node node, E e){
        if(node == null){
            size ++;
            return new Node(e);
        }

        if(e.compareTo(node.e) < 0)
            node.left = add(node.left, e);
        else if(e.compareTo(node.e) > 0)
            node.right = add(node.right, e);

        return node;
    }

    /**
     * 查看是否包含元素
     * @param e
     * @return
     */
    public boolean contains(E e) {
        return contains(root, e);
    }

    /**
     * 查看是否包含元素核心方法，递归
     * @param node
     * @param e
     * @return
     */
    private boolean contains(Node node, E e) {
        if(node == null)
            return false;

        if(e.compareTo(node.e) == 0)
            return true;
        else if(e.compareTo(node.e) < 0)
            return contains(node.left, e);
        else
            return contains(node.right, e);
    }

    /**
     * 二分搜索树的前序遍历
     */
    public void preOrder() {
        preOrder(root);
    }

    /**
     * 前序遍历核心函数， 递归
     * @param node
     */
    private void preOrder(Node node) {
        if(node == null) {
            return;
        }
        System.out.println(node.e);
        preOrder(node.left);
        preOrder(node.right);
    }

    /**
     * 中序遍历
     */
    public void inOrder() {
        inOrder(root);
    }

    /**
     * 中序遍历核心函数，递归，可以用来排序
     * @param node
     */
    private void inOrder(Node node) {
        if(node == null)
            return;
        inOrder(node.left);
        System.out.println(node.e);
        inOrder(node.right);

    }

    /**
     * 后续遍历
     */
    public void postOrder() {
        postOrder(root);
    }

    /**
     * 后续遍历核心函数，递归
     * @param node
     */
    private void postOrder(Node node) {
        if(node == null) {
            return;
        }
        postOrder(node.left);
        postOrder(node.right);
        System.out.println(node.e);
    }

    /**
     * 层序遍历
     */
    public void levelOrder() {
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            Node node = queue.remove();
            System.out.println(node.e);

            if(node.left != null)
                queue.add(node.left);
            if(node.right != null)
                queue.add(node.right);
        }
    }

    /**
     * 前序遍历非递归实现，使用栈后入先出的性质模拟系统栈
     */
    public void preOrderNR() {
        if(root == null)
            return;
        Stack<Node> stack = new Stack<Node>();
        stack.push(root);
        while(!stack.isEmpty()) {
            Node node = stack.pop();
            System.out.println(node.e);
            if(node.right != null) {
                stack.push(node.right);
            }
            if(node.left != null) {
                stack.push(node.left);
            }
        }

    }

    /**
     * 非递归中序遍历
     */
    public void inOrderNR() {
        Stack<Node> stack = new Stack<>();
        Node node = root;
        while(node != null || stack.size() > 0) {
            if(node != null) {
                stack.push(node);
                node = node.left;
            }else {
                node = stack.pop();
                System.out.println(node.e);
                node = node.right;
            }
        }
    }

    /**
     * 后续遍历，非递归
     */
    public void postOrderNR() { // 后序遍历
        Stack<Node> stack = new Stack<Node>();
        Stack<Node> output = new Stack<Node>();// 构造一个中间栈来存储逆后序遍历的结果
        Node node = root;
        while (node != null || stack.size() > 0) {
             if (node != null) {
                 output.push(node);
                 stack.push(node);
                 node = node.right;

             } else {
                 node = stack.pop();
                 node = node.left;
             }
        }
        while (output.size() > 0) {
            System.out.println(output.pop().e);
        }
    }

    /**
     * 查询二分搜索树的最小值
     * @return
     */
    public E minimum() {
        if(size == 0) {
            throw new IllegalArgumentException("BST is empty.");
        }
        return minimum(root).e;
    }

    /**
     * 寻找二分搜索树最小值核心函数，递归
     * @param node
     * @return
     */
    private Node minimum(Node node) {
        if(node.left == null)
            return node;
        return minimum(node.left);
    }

    /**
     * 寻找二分搜索树的最大值
     * @return
     */
    public E maximum() {
        if(size == 0)
            throw new IllegalArgumentException("BST is empty.");
        return maximum(root).e;
    }

    /**
     * 寻找二分搜索树最大值核心函数，递归
     * @param node
     * @return
     */
    private Node maximum(Node node) {
        if(node.right == null)
            return node;
        return maximum(node.right);
    }

    /**
     * 删除二分搜索树的最小值
     * @return
     */
    public E removeMin() {
        E ret = minimum();
        root = removeMin(root);
        return ret;
    }

    /**
     * 删除以node为根的二分搜索树的最小值，返回新的二分搜索树的根
     * @param node
     * @return
     */
    private Node removeMin(Node node) {
        if(node.left == null) {
            Node rightNode = node.right;
            node.right = null;
            size--;
            return rightNode;
        }
        node.left = removeMin(node.left);
        return node;
    }

    /**
     * 删除二分搜索树的最大值
     * @return
     */
    public E removeMax() {
        E ret = maximum();
        root = removeMax(root);
        return ret;
    }

    /**
     * 删除以node为根的二分搜索树的最大值，返回新的二分搜索树的根
     * @param node
     * @return
     */
    private Node removeMax(Node node) {
        if(node.right == null) {
            Node leftNode = node.left;
            node.left = null;
            size--;
            return leftNode;
        }
        node.right = removeMax(node);
        return node;
    }

    /**
     * 删除任意元素
     * @param e
     */
    public void remove(E e) {
        root = remove(root, e);
    }

    /**
     * 删除以node为根的二分搜索树的任意值，返回新的树的根
     * @param node
     * @param e
     * @return
     */
    private Node remove(Node node, E e) {
        if(node == null)
            return null;
        if(e.compareTo(node.e) < 0) {
            node.left = remove(node.left, e);
            return node;
        }else if(e.compareTo(node.e) > 0) {
            node.right = remove(node.right, e);
            return node;
        }else {
            if(node.left == null) {
                Node rightNode = node.right;
                node.right = null;
                size--;
                return rightNode;
            }
            if(node.right == null) {
                Node leftNode = node.left;
                node.left = null;
                size--;
                return leftNode;
            }
            Node successor = minimum(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;

            node.left = node.right = null;
            return successor;
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        generateBSTString(root, 0, sb);
        return sb.toString();
    }

    private void generateBSTString(Node node, int depth, StringBuilder sb) {
        if(node == null) {
            sb.append(generateDepthString(depth) + "null\n");
            return;
        }
        sb.append(generateDepthString(depth) + node.e + "\n");
        generateBSTString(node.left, depth + 1, sb);
        generateBSTString(node.right, depth + 1, sb);
    }

    private String generateDepthString(int depth) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < depth; i++) {
            sb.append("--");
        }
        return sb.toString();
    }

}
